package com.maya.medicalwastes.httpNet.interceptor;


import android.content.Context;
import android.util.Base64;

import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.util.CryptoTools;
import com.maya.medicalwastes.util.PrefUtils;
import com.maya.medicalwastes.util.StringUtils;

import java.io.IOException;
import java.util.UUID;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @description 在okhttp的请求头上增加cookie的拦截器
 * @user gzl
 * @date 2017/5/19
 * @time 14:46
 */

public class AddCookiesInterceptor implements Interceptor {
    protected static AddCookiesInterceptor instance;
    protected static Context mContext;
    private static String mHttpUrl;

    public static AddCookiesInterceptor getInstance(Context context, String url) {
        if (instance == null) {
            synchronized (AddCookiesInterceptor.class) {
                if (instance == null) {
                    instance = new AddCookiesInterceptor();
                }
            }
        }
        if (mContext == null) {
            mContext = context;
        }
        if (mHttpUrl == null) {
            mHttpUrl = url;
        }
        return instance;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("UUID", UUID.randomUUID().toString());
        builder.addHeader("User-Agent", "android").addHeader("Content-Type", "text/html; charset=utf-8").addHeader("Connection", "Keep-Alive");
        String safeCookie = null;
        String safeSession = PrefUtils.getString(mContext, SharedPreferencesConstant.SESSION, "");
        if (!StringUtils.isEmpty(safeSession)) {
            try {
                byte[] session = CryptoTools.des3EncodeECB(safeSession.getBytes("UTF-8"));
                safeCookie = new String(Base64.encode(session, Base64.DEFAULT), "UTF-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (safeCookie != null)
                try {
                    byte[] tmpt = Base64.decode(safeCookie.getBytes("UTF-8"), Base64.DEFAULT);
                    tmpt = CryptoTools.ees3DecodeECB(tmpt);
                    String cookie = new String(tmpt, "UTF-8");
                    builder.addHeader("Cookie", cookie);
                    builder.addHeader("Cookie", PrefUtils.getString(mContext, SharedPreferencesConstant.REMEMBER_ME, ""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
        return chain.proceed(builder.build());
    }

}
